package com.campus.food.service.impl;

import com.campus.food.mapper.AddressMapper;
import com.campus.food.model.entity.Address;
import com.campus.food.service.AddressService;
import com.campus.food.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 地址服务实现类
 * 
 * @author Claude3.7 Sonnet
 * @since 2025-05-29
 */
@Service
@Transactional
public class AddressServiceImpl implements AddressService {
    
    @Autowired
    private AddressMapper addressMapper;
    
    // 用户地址数量限制
    private static final int MAX_ADDRESS_COUNT = 20;
    
    @Override
    public Address addAddress(Address address) {
        // 验证必填字段
        validateAddress(address);
        
        // 检查用户地址数量限制
        long addressCount = addressMapper.selectCountByUserId(address.getUserId());
        if (addressCount >= MAX_ADDRESS_COUNT) {
            throw new BusinessException("地址数量已达上限，最多可添加" + MAX_ADDRESS_COUNT + "个地址");
        }
        
        // 如果是第一个地址或者设置为默认地址，需要处理默认地址逻辑
        if (address.getIsDefault() == 1 || addressCount == 0) {
            // 清除用户的其他默认地址
            addressMapper.clearDefaultByUserId(address.getUserId());
            address.setIsDefault(1);
        } else {
            address.setIsDefault(0);
        }
        
        // 保存地址
        int result = addressMapper.insert(address);
        if (result <= 0) {
            throw new BusinessException("添加地址失败");
        }
        
        return address;
    }
    
    @Override
    @Transactional(readOnly = true)
    public Address getAddressById(Long id) {
        if (id == null) {
            throw new BusinessException("地址ID不能为空");
        }
        
        Address address = addressMapper.selectById(id);
        if (address == null) {
            throw new BusinessException("地址不存在");
        }
        
        return address;
    }
    
    @Override
    public boolean updateAddress(Address address) {
        if (address.getId() == null) {
            throw new BusinessException("地址ID不能为空");
        }
        
        // 验证必填字段
        validateAddress(address);
        
        // 检查地址是否存在
        Address existingAddress = addressMapper.selectById(address.getId());
        if (existingAddress == null) {
            throw new BusinessException("地址不存在");
        }
        
        // 验证权限（确保只能修改自己的地址）
        if (!existingAddress.getUserId().equals(address.getUserId())) {
            throw new BusinessException("无权限修改此地址");
        }
        
        // 如果设置为默认地址，需要清除其他默认地址
        if (address.getIsDefault() == 1) {
            addressMapper.clearDefaultByUserId(address.getUserId());
        }
        
        return addressMapper.updateById(address) > 0;
    }
    
    @Override
    public boolean deleteAddress(Long id, Long userId) {
        if (id == null) {
            throw new BusinessException("地址ID不能为空");
        }
        
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }
        
        // 检查地址是否存在
        Address address = addressMapper.selectById(id);
        if (address == null) {
            throw new BusinessException("地址不存在");
        }
        
        // 验证权限（确保只能删除自己的地址）
        if (!address.getUserId().equals(userId)) {
            throw new BusinessException("无权限删除此地址");
        }
        
        // 删除地址
        boolean result = addressMapper.deleteById(id) > 0;
        
        // 如果删除的是默认地址，需要重新设置默认地址
        if (result && address.getIsDefault() == 1) {
            List<Address> userAddresses = addressMapper.selectByUserId(userId);
            if (!userAddresses.isEmpty()) {
                // 将第一个地址设为默认地址
                addressMapper.setDefault(userAddresses.get(0).getId());
            }
        }
        
        return result;
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Address> getAddressByUserId(Long userId) {
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }
        
        return addressMapper.selectByUserId(userId);
    }
    
    @Override
    @Transactional(readOnly = true)
    public Address getDefaultAddress(Long userId) {
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }
        
        return addressMapper.selectDefaultByUserId(userId);
    }
    
    @Override
    public boolean setDefaultAddress(Long id, Long userId) {
        if (id == null) {
            throw new BusinessException("地址ID不能为空");
        }
        
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }
        
        // 检查地址是否存在
        Address address = addressMapper.selectById(id);
        if (address == null) {
            throw new BusinessException("地址不存在");
        }
        
        // 验证权限（确保只能设置自己的地址为默认）
        if (!address.getUserId().equals(userId)) {
            throw new BusinessException("无权限设置此地址为默认");
        }
        
        // 清除用户的其他默认地址
        addressMapper.clearDefaultByUserId(userId);
        
        // 设置指定地址为默认地址
        return addressMapper.setDefault(id) > 0;
    }
    
    @Override
    @Transactional(readOnly = true)
    public long getAddressCount(Long userId) {
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }
        
        return addressMapper.selectCountByUserId(userId);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Address> searchAddress(Long userId, String keyword) {
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }
        
        return addressMapper.searchByUserIdAndKeyword(userId, keyword);
    }
    
    @Override
    public boolean deleteAddressBatch(List<Long> ids, Long userId) {
        if (ids == null || ids.isEmpty()) {
            throw new BusinessException("地址ID列表不能为空");
        }
        
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }
        
        // 验证所有地址都属于当前用户
        for (Long id : ids) {
            Address address = addressMapper.selectById(id);
            if (address == null) {
                throw new BusinessException("地址不存在：" + id);
            }
            if (!address.getUserId().equals(userId)) {
                throw new BusinessException("无权限删除地址：" + id);
            }
        }
        
        // 批量删除
        boolean result = addressMapper.deleteBatch(ids) > 0;
        
        // 检查是否删除了默认地址，如果是则重新设置默认地址
        if (result) {
            Address defaultAddress = addressMapper.selectDefaultByUserId(userId);
            if (defaultAddress == null) {
                List<Address> userAddresses = addressMapper.selectByUserId(userId);
                if (!userAddresses.isEmpty()) {
                    addressMapper.setDefault(userAddresses.get(0).getId());
                }
            }
        }
        
        return result;
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Address> getAllAddresses(int page, int size, Long userId) {
        int offset = (page - 1) * size;
        return addressMapper.selectAllForAdmin(offset, size, userId);
    }
    
    /**
     * 验证地址信息
     */
    private void validateAddress(Address address) {
        if (address == null) {
            throw new BusinessException("地址信息不能为空");
        }
        
        if (address.getUserId() == null) {
            throw new BusinessException("用户ID不能为空");
        }
        
        if (!StringUtils.hasText(address.getReceiverName())) {
            throw new BusinessException("收件人姓名不能为空");
        }
        
        if (!StringUtils.hasText(address.getReceiverPhone())) {
            throw new BusinessException("收件人电话不能为空");
        }
        
        if (!StringUtils.hasText(address.getProvince())) {
            throw new BusinessException("省份不能为空");
        }
        
        if (!StringUtils.hasText(address.getCity())) {
            throw new BusinessException("城市不能为空");
        }
        
        if (!StringUtils.hasText(address.getDistrict())) {
            throw new BusinessException("区县不能为空");
        }
        
        if (!StringUtils.hasText(address.getDetailAddress())) {
            throw new BusinessException("详细地址不能为空");
        }
        
        // 验证手机号格式
        if (!address.getReceiverPhone().matches("^1[3-9]\\d{9}$")) {
            throw new BusinessException("手机号格式不正确");
        }
    }
} 